//
//  processDetailViewController.m
//  salesTerminals
//
//  Created by wu haifan on 12-9-5.
//  Copyright (c) 2012年 MICHAEL. All rights reserved.
//

#import "processDetailViewController.h"
#import "TSActionSheet.h"
#import "TSPopoverController.h"
#import "processEventListViewController.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "JSONKit.h"

@interface processDetailViewController ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate,ASIHTTPRequestDelegate,UIWebViewDelegate>

@property(strong,nonatomic) UITableView* myDetailView;
@property (nonatomic, strong) UIAlertView *alertSuccess;
@property (nonatomic, strong) MBProgressHUD* mbprogress;


@end

@implementation processDetailViewController

@synthesize myDetailView=_myDetailView;
NSDictionary* totalDictory;
NSArray* eventDetailArray;
ASIFormDataRequest *requestBackOff;
ASIFormDataRequest *requestCancel;
NSArray* arrayBackOff;
NSString* cancelEventId;
NSString* userId;
NSArray* cancelResultArray;
@synthesize mbprogress=_mbprogress;
@synthesize alertSuccess=_alertSuccess;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title=@"审批明细";
    self.view.contentMode = UIViewContentModeScaleAspectFill;
    
    self.myDetailView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width,
                                                                      self.view.bounds.size.height)
                                                     style:UITableViewStylePlain];
    [self.myDetailView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    [self.myDetailView setDelegate:self];
    [self.myDetailView setDataSource:self];
    [self.myDetailView setEditing:NO animated:NO];
//    [self.myDetailView setBackgroundColor:[UIColor cyanColor]];
    [self.view addSubview: self.myDetailView];
    NSString * s = [totalDictory objectForKey:@"initator"];
    NSString * r = [totalDictory objectForKey:@"status"];
    if([r isEqualToString:@"0"] || [r isEqualToString:@"1"] ){
        if ([s isEqualToString:@"50354"] ){
            UIBarButtonItem *topRightButton = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleBordered target:self action:@selector(cancel:forEvent:)];
            self.navigationItem.rightBarButtonItem = topRightButton;
        }
    }
    cancelEventId = [totalDictory objectForKey:@"eventId"];
}


-(void) viewWillAppear:(BOOL)animated {
    
    NSString* u=@"http://10.32.50.145:8080/xplatform/router/rest";
    NSURL *url = [NSURL URLWithString:u];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    [request addPostValue: @"getEventDetailListAndSort" forKey:@"method"];
    [request addPostValue: [totalDictory objectForKey:@"eventId"] forKey:@"eventId"];
    [request setDelegate:self];
    [request start];
    
    //预先加载回退处理人
    NSString* u2=@"http://10.32.50.145:8080/xplatform/router/rest";
    NSURL *url2= [NSURL URLWithString:u2];
    requestBackOff = [ASIFormDataRequest requestWithURL:url2];
    [requestBackOff addPostValue: @"getRollbackEventDetailList" forKey:@"method"];
    [requestBackOff addPostValue: [totalDictory objectForKey:@"eventId"] forKey:@"eventId"];//
    [requestBackOff setDelegate:self];
    [requestBackOff start];
    
    [self showMbprogress];
    
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return [NSString stringWithFormat:@"Title：%@",[totalDictory objectForKey:@"eventTitle"]];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [eventDetailArray count];
}

//row高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.row==0){
        return 275;
    }else {
        return 100;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString* CellIdentifier = [NSString stringWithFormat:@"%d%d",indexPath.section, indexPath.row];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    for (UIView *v in [cell subviews]) {
        if ([v isKindOfClass:[UILabel class]] |
            [v isKindOfClass:[UITextView class]]) {
            [v removeFromSuperview];
        }
    }
    //事务处理人
    UILabel*tempLabel4operator = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 100, 15)];
    NSUInteger index = [indexPath row];
    NSDictionary*detail=[eventDetailArray objectAtIndex:index];
    
    if(index==0)
    {
        [tempLabel4operator setText:[[NSString alloc] initWithFormat:@"发起人：%@",[detail objectForKey:@"userName"]]];
        userId = [detail objectForKey:@"curUserId"];
    }else {
        
        [tempLabel4operator setText:[[NSString alloc] initWithFormat:@"处理人：%@",[detail objectForKey:@"userName"]]];
    }
    tempLabel4operator.font = [UIFont systemFontOfSize:12];
    [tempLabel4operator setTextColor:[UIColor colorWithRed:9/255.0 green:119/255.0 blue:179/255.0 alpha:1.0]];
    [tempLabel4operator setBackgroundColor:[UIColor clearColor]];
    [cell addSubview:tempLabel4operator];
    
    //职位
    UILabel*tempLabel4position = [[UILabel alloc] initWithFrame:CGRectMake(110, 5, 300, 15)];
    [tempLabel4position setText:[[NSString alloc] initWithFormat:@"职位：%@",[detail objectForKey:@"roleName"]]];
    tempLabel4position.font = [UIFont systemFontOfSize:12];
    [tempLabel4position setTextColor:[UIColor colorWithRed:9/255.0 green:119/255.0 blue:179/255.0 alpha:1.0]];
    [tempLabel4position setBackgroundColor:[UIColor clearColor]];
    [cell addSubview:tempLabel4position];
    
    if(indexPath.row==0){
        //内容
        UILabel*tempLabel4content = [[UILabel alloc] initWithFrame:CGRectMake(10, 25, 320, 20)];
        [tempLabel4content setText:[[NSString alloc] initWithFormat:@"内  容"]];
        tempLabel4content.font = [UIFont systemFontOfSize:13];
        [tempLabel4content setTextColor:[UIColor colorWithRed:9/255.0 green:119/255.0 blue:179/255.0 alpha:1.0]];
        [tempLabel4content setBackgroundColor:[UIColor clearColor]];
        [cell addSubview:tempLabel4content];
        
        //获取内容url
        NSMutableString *urlSearch = [NSMutableString stringWithFormat:@"http://ims.nfsq.com.cn:8191/xplatform"];
        UIWebView*tempWebview4content =[[UIWebView alloc] initWithFrame:CGRectMake(50, 25, 248, 200)];
        [tempWebview4content setScalesPageToFit:YES];
        [tempWebview4content loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[urlSearch stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
        [cell addSubview:tempWebview4content];
        
        //备注
        UILabel*tempLabel4remark = [[UILabel alloc] initWithFrame:CGRectMake(10, 230, 320, 15)];
        [tempLabel4remark setText:[[NSString alloc] initWithFormat:@"备注    ：%@",[detail objectForKey:@"memo"]]];
        [tempLabel4remark setTextColor:[UIColor colorWithRed:9/255.0 green:119/255.0 blue:179/255.0 alpha:1.0]];
        tempLabel4remark.font = [UIFont systemFontOfSize:12];
        [tempLabel4remark setBackgroundColor:[UIColor clearColor]];
        [cell addSubview:tempLabel4remark];
        
        //附件
        UILabel*tempLabel4annex = [[UILabel alloc] initWithFrame:CGRectMake(10, 253, 320, 15)];
        [tempLabel4annex setText:[[NSString alloc] initWithFormat:@"附件    ："]];
        [tempLabel4annex setTextColor:[UIColor colorWithRed:9/255.0 green:119/255.0 blue:179/255.0 alpha:1.0]];
        tempLabel4annex.font = [UIFont systemFontOfSize:12];
        [tempLabel4annex setBackgroundColor:[UIColor clearColor]];
        [cell addSubview:tempLabel4annex];
        
        //附件url
        UIWebView*tempWebview4annex =[[UIWebView alloc] initWithFrame:CGRectMake(60, 250, 248, 20)];
        tempWebview4annex.delegate=self;
        [tempWebview4annex setScalesPageToFit:YES];
        [[[tempWebview4annex subviews] objectAtIndex:0] setScrollEnabled:NO];//禁用scroll
        NSString*htmlStr=@"<body bgcolor=\"cyan\"><a charset=\"UTF-8\" href=\"button.gif\"><font size=8>测试附件ddcdcd.GIF</font></a></body>";
        [tempWebview4annex loadHTMLString:htmlStr baseURL:[NSURL URLWithString:@"http://10.32.50.154:8080/xplatform/"]];
        [cell addSubview:tempWebview4annex];
        
        
        
    }else {
        //操作状态
        UILabel*tempLabel4operaState = [[UILabel alloc] initWithFrame:CGRectMake(10, 25, 320, 20)];
        NSString* stateString;
        if([[detail objectForKey:@"operation"] isEqualToString:@"1"]){
            stateString=@"同意";
        }else {
            stateString=@"未处理";
        }
        [tempLabel4operaState setText:[[NSString alloc] initWithFormat:@"状态    ：%@",stateString]];
        [tempLabel4operaState setTextColor:[UIColor colorWithRed:9/255.0 green:119/255.0 blue:179/255.0 alpha:1.0]];
        tempLabel4operaState.font = [UIFont systemFontOfSize:12];
        [tempLabel4operaState setBackgroundColor:[UIColor clearColor]];
        [cell addSubview:tempLabel4operaState];
        
        //事务处理时间
        UILabel*tempLabel4operatDate = [[UILabel alloc] initWithFrame:CGRectMake(110, 25, 200, 15)];
        [tempLabel4operatDate setText:[[NSString alloc] initWithFormat:@"时间：2012-08-01 12:30"]];
        tempLabel4operatDate.font = [UIFont systemFontOfSize:12];
        [tempLabel4operatDate setTextColor:[UIColor colorWithRed:9/255.0 green:119/255.0 blue:179/255.0 alpha:1.0]];
        [tempLabel4operatDate setBackgroundColor:[UIColor clearColor]];
        [cell addSubview:tempLabel4operatDate];
        
        //意见
        UILabel*tempLabel4suggest = [[UILabel alloc] initWithFrame:CGRectMake(10, 50, 320, 20)];
        [tempLabel4suggest setText:[[NSString alloc] initWithFormat:@"意见    ：%@",[detail objectForKey:@"memo"]]];
        [tempLabel4suggest setTextColor:[UIColor colorWithRed:9/255.0 green:119/255.0 blue:179/255.0 alpha:1.0]];
        tempLabel4suggest.font = [UIFont systemFontOfSize:12];
        [tempLabel4suggest setBackgroundColor:[UIColor clearColor]];
        [cell addSubview:tempLabel4suggest];
        
        //附件
        UILabel*tempLabel4annex = [[UILabel alloc] initWithFrame:CGRectMake(10, 78, 320, 20)];
        [tempLabel4annex setText:[[NSString alloc] initWithFormat:@"附件    ："]];
        [tempLabel4annex setTextColor:[UIColor colorWithRed:9/255.0 green:119/255.0 blue:179/255.0 alpha:1.0]];
        tempLabel4annex.font = [UIFont systemFontOfSize:12];
        [tempLabel4annex setBackgroundColor:[UIColor clearColor]];
        [cell addSubview:tempLabel4annex];
        
        //附件url
        UIWebView*tempWebview4annex =[[UIWebView alloc] initWithFrame:CGRectMake(60, 77, 248, 20)];
        tempWebview4annex.delegate=self;
        [[[tempWebview4annex subviews] objectAtIndex:0] setScrollEnabled:NO];//禁用scroll
        [tempWebview4annex setScalesPageToFit:YES];
        NSString*htmlStr=@"<body bgcolor=\"cyan\"><a charset=\"UTF-8\" href=\"button.xls\"><font size=8>测试附件ddcdcd.xls</a><font></body>";
        [tempWebview4annex loadHTMLString:htmlStr baseURL:[NSURL URLWithString:@"http://10.32.50.154:8080/xplatform/"]];
        [cell addSubview:tempWebview4annex];
        
//        UIImage* seletedImg = [UIImage imageNamed:@"tableviewcellSelected.png"];
//        UIImageView *seletedImgView =[[UIImageView alloc] initWithImage:seletedImg];
//        [cell setSelectedBackgroundView:seletedImgView];
//        
//        
//        UIImage* backImg = [UIImage imageNamed:@"tableviewcell.png"];
//        UIImageView *backImgView =[[UIImageView alloc] initWithImage:backImg];
//        [cell setBackgroundView:backImgView];
        
    }
    
    return cell;
    
}

//popover
-(void)showPopover:(id)sender forEvent:(UIEvent*)event
{
    UITableViewController *tableViewController = [[UITableViewController alloc] initWithStyle:UITableViewStylePlain];
    tableViewController.view.frame = CGRectMake(0,0, 320, 400);
    TSPopoverController *popoverController = [[TSPopoverController alloc] initWithContentViewController:tableViewController];
    popoverController.cornerRadius = 5;
    popoverController.titleText = @"change order";
    popoverController.popoverBaseColor = [UIColor lightGrayColor];
    popoverController.popoverGradient= NO;
    [popoverController showPopoverWithTouch:event];
    
}

-(void)passFromtotal:(NSDictionary*)total{
    totalDictory=total;
}



- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

- (void)requestFinished:(ASIHTTPRequest *)request {
    
    NSError *error = [request error];
    //回退处理人请求
    if(request==requestBackOff){
        if (!error) {
            NSString *res = [request responseString];
            arrayBackOff= [res objectFromJSONString];
        }
    }else if (request == requestCancel) {
        NSString *res = [request responseString];
        
        if([res isEqualToString:@"true"])
        {
            [self hideMbProgressSuccess];
        }else{
            [self hideMbProgressFail];
        }
    }else{
        if (!error) {
            NSString *res = [request responseString];
            eventDetailArray= [res objectFromJSONString];
        }
        [self.myDetailView reloadData];
    }
    [self hideMbProgress];
    
}

-(BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    if(navigationType==UIWebViewNavigationTypeLinkClicked)
    {
        [[UIApplication sharedApplication] openURL:[request URL]];
    }
    return YES;
}
-(void) cancel:(id)sender forEvent:(UIEvent*)event
{
    NSString* u=@"http://10.32.50.145:8080/xplatform/router/rest";
    NSURL *url = [NSURL URLWithString:u];
    requestCancel= [ASIFormDataRequest requestWithURL:url];
    [requestCancel addPostValue: @"cancelEvent" forKey:@"method"];
    [requestCancel addPostValue: cancelEventId forKey:@"eventId"];
    [requestCancel setDelegate:self];
    [self showMbprogress];
    [requestCancel start];
}
-(void) hideMbProgressSuccess {
    [self.mbprogress hide:YES];
    self.alertSuccess = [[UIAlertView alloc] initWithTitle:@"事务取消" message:@"取消成功!"
                                                  delegate:self cancelButtonTitle:nil otherButtonTitles: @"OK",nil];
    [self.alertSuccess show];
}
-(void) hideMbProgressFail {
    [self.mbprogress hide:YES];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"事务取消" message:@"取消失败!请稍后再试"
                                                   delegate:self cancelButtonTitle:nil otherButtonTitles: @"OK",nil];
    [alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView == self.alertSuccess)
    {
        //回代办首页
        processEventListViewController*dealWithView=[[processEventListViewController alloc] init];
        [self.navigationController pushViewController:dealWithView animated:YES];    }
}

@end

